package com.aote.model;

import javax.servlet.http.HttpServletRequest;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.aote.util.StringHelper;
import com.browsesoft.Entity;
import com.browsesoft.EntityManager;
import com.browsesoft.PropertiesService;
import com.browsesoft.dbtools.DBTools;

/**
 * 可执行属性文件中配置的一批sql的动作类
 * 
 */
public class DoSqlAction implements Action {

	private Entity entity = null;

	/**
	 * 执行属性文件中配置的sql动作
	 */
	public void doAction(HttpServletRequest request) {
		String id = request.getParameter("id");
		entity = getEntity(id);
		// 根据sql名称从属性文件中得到sql
		String sqlName = request.getParameter("sql");
		Element sqlElem = this.getSqlElement(sqlName);
		if (sqlElem == null) {
			throw new RuntimeException("未在属性文件中找到sql=" + sqlName + "的配置");
		}
		// 得到配置元素，得到所有sql,执行
		executeSql(sqlElem);
	}

	/*
	 * 根据名称得到sql配置元素
	 */
	private Element getSqlElement(String sqlName) {
		NodeList list = PropertiesService.getDocument().getElementsByTagName(
				"sql");
		for (int i = 0; i < list.getLength(); i++) {
			Element elem = (Element) list.item(i);
			String name = (String) elem.getAttribute("name");
			if (name != null && name.equals(sqlName)) {
				return elem;
			}
		}
		return null;
	}

	/**
	 * 根据id得到实体
	 */
	private Entity getEntity(String id) {
		return (Entity) EntityManager.getInstance().getObject(id);
	}

	/**
	 * 执行sql语句
	 */
	private void executeSql(Element elem) {
		NodeList sentences = elem.getElementsByTagName("sentence");
		for (int i = 0; i < sentences.getLength(); i++) {
			Element sentence = (Element) sentences.item(i);
			String sql = sentence.getAttribute("value");
			if (this.entity != null) {
				// 用实体属性替换sql
				sql = StringHelper.replaceStr(entity.getAttributes(),sql);
			}
			try {
				DBTools.excuteUpdate(sql);
			} catch (Exception e) {
				throw new RuntimeException("执行sql:" + sql + "错误", e);
			}
		}
	}


}
